<?php
namespace app\system\service;
use think\facade\Db;

class MenuRoutesService{
    /**
     * 描述:获取角色菜单的列表
     * 参数:{}
     * 返回:
     * 作者:W
     */
    public function getAsyncRoutes(){
        // 查询菜单数据和相关角色信息
        $menuRoutesList = Db::name('menus')
            ->alias('m')
            ->leftJoin('role_menu rm', 'm.id = rm.menuId')
            ->leftJoin('roles r', 'rm.roleId = r.id')
            ->field('m.*, GROUP_CONCAT(r.code) AS roles')
            ->whereNull('m.deleteTime')  // 确保 deleteTime 字段为 NULL
            ->group('m.id')
            ->order('m.parentId, m.rank')
            ->select()
            ->toArray();

        $res = $this->buildMenuTree($menuRoutesList);
        $systemManagementRouter = $this->transformMenuTree($res);
        return $systemManagementRouter;
    }

    /**
     * 描述:将菜单数据转换为树形结构
     * 参数:{}
     * 返回:
     * 作者:W
     */
    public function buildMenuTree(array $elements, $parentId = 0) {
        $branch = [];
        foreach ($elements as $element) {
            if ($element['parentId'] == $parentId) {
                $children = $this->buildMenuTree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }

    /**
     * 描述:转换为目标格式
     * 参数:{}
     * 返回:
     * 作者:W
     */
    public  function transformMenuTree($menuTree, $isChild = false) {
        $result = [];
        foreach ($menuTree as $menu) {
            $menuData = [
                "path" => $menu['path'],
                "meta" => [
                    "icon" => $menu['icon'],
                    "title" => $menu['title']
                ]
            ];
            if (!empty($menu['name'])) {
                $menuData["name"] = $menu['name'];
            }

            if (!$isChild && !empty($menu['rank'])) {
                $menuData["meta"]["rank"] = $menu['rank'];
            }
            // 添加 roles 字段，顶级菜单项不需要包含 roles 字段
            if (!empty($menu['roles'])) {
                $menuData['meta']["roles"] = explode(',', $menu['roles']); // 将角色字符串转换为数组
            } else {
                $menuData['meta']["roles"] = []; // 如果 roles 为空，添加一个空数组
            }

            if (!empty($menu['children'])) {
                $menuData['children'] = $this->transformMenuTree($menu['children'], true);
            }

            $result[] = $menuData;
        }
        return $result;
    }
}